<?php
/**
 * Created by PhpStorm.
 * User: yuesir
 * Date: 2017/6/5
 * Time: 上午12:09
 */

namespace app\lib\exception;


use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    //http状态码
    private $code;
    //错误消息
    private $msg;
    //错误码
    private $errorCode;

    public function render(\Exception $e)
    {
        if ($e instanceof BaseException) {
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        } else {
            if (config('app_debug')) {
                return parent::render($e);
            }

            $this->code = 400;
            $this->msg = '服务器错误,不想告诉你';
            $this->errorCode = 999;
            $this->logError($e);
        }

        $result = [
            'error_code'    => $this->errorCode,
            'msg'           => $this->msg,
            'request_url'   => Request::instance()->url()
        ];

        return json($result, $this->code);
    }

    /**
     * 记录 log
     * @param Exception $e
     */
    protected function logError(\Exception $e)
    {
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            // 日志记录级别
            'level' => ['error'],
        ]);

        Log::record($e->getMessage(), 'error');
    }
}